package com.app.studyroom;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.adapter.AnnouncementAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.message.AnnouncementItem;
import com.app.studyroom.api.model.message.MessageIndexResponse;
import com.app.studyroom.api.model.message.MessagePageRequest;
import com.app.studyroom.api.model.message.MessagePageResponse;
import com.app.studyroom.mapper.AnnouncementTypeMapper;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AdminAnnouncementControlActivity extends BaseActivity {

    private Spinner spinnerMessageType;
    private EditText editMessageContent;
    private Button btnPublishMessage, btnPrevPage, btnNextPage;
    private ImageView ic_back;
    private TextView tvPageIndicator;
    private RecyclerView recyclerView;
    private AnnouncementAdapter announcementAdapter;

    private List<AnnouncementItem> allAnnouncements = new ArrayList<>();
    private static final int PAGE_SIZE = 11;
    private int currentPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_announcement_control);

        spinnerMessageType = findViewById(R.id.spinnerMessageType);
        editMessageContent = findViewById(R.id.editMessageContent);
        btnPublishMessage = findViewById(R.id.btnPublishMessage);
        ic_back = findViewById(R.id.ic_back);
        recyclerView = findViewById(R.id.recyclerViewAnnouncements);
        btnPrevPage = findViewById(R.id.btnPrevPage);
        btnNextPage = findViewById(R.id.btnNextPage);
        tvPageIndicator = findViewById(R.id.tvPageIndicator);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        announcementAdapter = new AnnouncementAdapter(this, new ArrayList<>(), item -> {
            deleteAnnouncement(String.valueOf(item.getId()));
        });
        recyclerView.setAdapter(announcementAdapter);

        // 初始化公告类型
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                AnnouncementTypeMapper.getAllChineseTypes()
        );
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMessageType.setAdapter(typeAdapter);

        ic_back.setOnClickListener(v -> onBackPressed());
        btnPublishMessage.setOnClickListener(v -> publishAnnouncement());

        btnPrevPage.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                loadAnnouncements();
            }
        });

        btnNextPage.setOnClickListener(v -> {
            int maxPage = (int) Math.ceil(allAnnouncements.size() / (double) PAGE_SIZE);
            if (currentPage < maxPage) {
                currentPage++;
                loadAnnouncements();
            }
        });

        loadAnnouncements();
    }

    private void publishAnnouncement() {
        String selectedChinese = spinnerMessageType.getSelectedItem().toString();
        String messageType = AnnouncementTypeMapper.toEnglish(selectedChinese);
        String message = editMessageContent.getText().toString().trim();
        String timestamp = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

        if (message.isEmpty()) {
            Toast.makeText(this, "请输入公告内容", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("timestamp", timestamp);
        requestBody.put("message", message);
        requestBody.put("messageType", messageType);

        Log.d("PublishRequest", "请求体: " + new Gson().toJson(requestBody));

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.publishAnnouncement(requestBody).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(AdminAnnouncementControlActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                    editMessageContent.setText("");
                    loadAnnouncements(); // 重新加载列表
                } else {
                    Toast.makeText(AdminAnnouncementControlActivity.this, "发布失败：" +
                            (response.body() != null ? response.body().getMessage() : "未知错误"), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(AdminAnnouncementControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void loadAnnouncements() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", "");

        MessagePageRequest request = new MessagePageRequest(currentPage, PAGE_SIZE);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);

        apiService.getMessagePage(token, request).enqueue(new Callback<ApiResponse<MessagePageResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<MessagePageResponse>> call, Response<ApiResponse<MessagePageResponse>> response) {

                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<AnnouncementItem> list = response.body().getData().getData();
                    int total = response.body().getData().getTotal();

                    allAnnouncements = list;
                    updateDisplayedPage(total);
                } else {
                    Toast.makeText(AdminAnnouncementControlActivity.this, "加载公告失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<MessagePageResponse>> call, Throwable t) {
                Log.e("TestResponse", "请求失败: " + t.getMessage(), t);
                Toast.makeText(AdminAnnouncementControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void deleteAnnouncement(String id) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", "");

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("id", id);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.deleteMessage(token, requestBody).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(AdminAnnouncementControlActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    loadAnnouncements(); // 重新加载
                } else {
                    Toast.makeText(AdminAnnouncementControlActivity.this, "删除失败：" +
                            (response.body() != null ? response.body().getMessage() : "未知错误"), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(AdminAnnouncementControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void updateDisplayedPage(int total) {
        tvPageIndicator.setText("第 " + currentPage + " 页");

        announcementAdapter.updateData(allAnnouncements);

        btnPrevPage.setEnabled(currentPage > 1);
        btnPrevPage.setAlpha(currentPage > 1 ? 1f : 0.4f);

        boolean isLastPage = currentPage * PAGE_SIZE >= total;
        btnNextPage.setEnabled(!isLastPage);
        btnNextPage.setAlpha(!isLastPage ? 1f : 0.4f);
    }

}
